﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using WinFormsApp1.Models;

namespace WinFormsApp1
{
    public partial class FrmMain : Form
    {
        private readonly Timer _timer;
        private int _counter;
        private readonly Random _random;
        private ButtonCollection _buttonCollection;

        /// <summary>
        /// 生成按钮的数量
        /// </summary>
        private int _maxButtonCount = 10;

        private int _maxTryCount = 1000;

        public FrmMain()
        {
            _timer = new Timer
            {
                Interval = 2000
            };
            _timer.Tick += TickHandler;
            _random = new Random();
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            _counter = 0;
            _buttonCollection = new ButtonCollection();
        }

        private void TickHandler(object sender, EventArgs e)
        {
            RandomShow();
        }

        private List<Button> _buttons = new List<Button>();

        /// <summary>
        /// 随机出现
        /// </summary>
        private void RandomShow()
        {
            ClearButtons();
            var minWidth = 90;
            var maxWidth = ClientSize.Width / _maxButtonCount;
            if (minWidth > maxWidth)
            {
                minWidth = maxWidth - 10;
            }
            for (var i = 0; i < _maxButtonCount; i++)
            {
                var w = _random.Next(minWidth,maxWidth );
                var h = _random.Next(40, ClientSize.Height / _maxButtonCount);
                var x = _random.Next(0, ClientSize.Width - w);
                var y = _random.Next(0, ClientSize.Height - h);
                var rect = new Rectangle(x, y, w, h);
                var isOverLap = false;
                var tryCount = 0;
                while (_buttons.Count > 0)
                {
                    // 1,2,3,4 len=4,count=4
                    foreach (var b in _buttons)
                    {
                        var r = new Rectangle(b.Location.X, b.Location.Y, b.Width, b.Height);
                        isOverLap = Rectangle.Intersect(rect, r) != Rectangle.Empty;
                        if (isOverLap)
                        {
                            break;
                        }
                    }

                    if (!isOverLap)
                    {
                        break;
                    }

                    x = _random.Next(0, ClientSize.Width - w);
                    y = _random.Next(0, ClientSize.Height - h);
                    rect.X = x;
                    rect.Y = y;
                    tryCount++;
                    if (tryCount > _maxTryCount)
                    {
                        MessageBox.Show("没有足够的空间了。");
                        break;
                    }
                }

                var btn = new Button
                {
                    Width = w,
                    Height = h,
                    Location = new Point(rect.X, rect.Y),
                    Text = $"({i})[x:{rect.X},y:{rect.Y}],[w:{w},h:{h}]",
                    Name = $"btn_rand_{i}",
                    Tag = $"w:{w},h:{h}",
                    Font = new Font(FontFamily.Families[2],8)
                    
                };

                Controls.Add(btn);
                _buttons.Add(btn);
                Application.DoEvents();
            }

            PrepareTooltips();
        }

        /// <summary>
        /// 会累加生成的控件
        /// </summary>
        private void DynamicCreate()
        {
            for (var i = _counter; i < 3 + _counter; i++)
            {
                var width = _random.Next(50, ClientSize.Width / 3);
                var height = _random.Next(25, ClientSize.Height / 3);
                int x = 0, y = 0;
                if (_buttonCollection.CurrentRowTotalWidth + width + ButtonCollection.Span > ClientSize.Width)
                {
                    // 新增一行
                    _buttonCollection.TotalHeight += _buttonCollection.Rows[_buttonCollection.RowIndex].MaxHeight;

                    _buttonCollection.RowIndex += 1;
                    _buttonCollection.Rows.Add(new RowItem());
                }
                else
                {
                    if (_buttonCollection.TotalButtonCount > 0 &&
                        _buttonCollection.Rows[_buttonCollection.RowIndex].Buttons.Count > 0)
                    {
                        //同一行还可以放
                        x = _buttonCollection.CurrentRowTotalWidth + ButtonCollection.Span;
                    }
                }

                if (_buttonCollection.TotalHeight >= ClientSize.Height - ButtonCollection.Span - height)
                {
                    _timer.Enabled = false;
                    MessageBox.Show("空间不足，已停止生成按钮");
                    break;
                }

                y = _buttonCollection.TotalHeight + ButtonCollection.Span;
                var btn = new Button
                {
                    Name = $"btn_rnd_{i}",
                    Size = new Size(width, height),
                    Margin = Padding.Empty,
                    Padding = Padding.Empty,
                    Text =
                        $"按钮{i + _counter}(x={x},y={y},w={width},h={height}),{_buttonCollection.RowIndex},{_buttonCollection.TotalHeight}",
                    Location = new Point(x, y)
                };
                this.Controls.Add(btn);
                _buttonCollection.TotalButtonCount++;

                _buttonCollection.Rows[_buttonCollection.RowIndex].AddButton(btn);
                Application.DoEvents();
            }

            _counter += 3;
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            label1.Text = $"控件数量:{_maxButtonCount}";
        }

        private ToolTip ToolTip1;

        private void PrepareTooltips()
        {
            ToolTip1 = new System.Windows.Forms.ToolTip();
            foreach (Control ctrl in this.Controls)
            {
                if (ctrl is Button && ctrl.Tag is string)
                {
                    ctrl.MouseHover += new EventHandler(delegate(Object o, EventArgs a)
                    {
                        var btn = (Control) o;
                        ToolTip1.SetToolTip(btn, btn.Tag.ToString());
                    });
                }
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            RandomShow();
            _timer.Enabled = true;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearButtons();
            _timer.Enabled = false;
        }

        private void ClearButtons()
        {
            if (_buttons.Count <= 0)
            {
                return;
            }

            foreach (Button btn in _buttons)
            {
                Controls.RemoveByKey(btn.Name);
            }

            _buttons.Clear();
        }
    }
}